<template>
  <div id="gzl-upload">
    <el-upload
      :disabled="disabled"
      class="upload-demo"
      :headers="headers"
      :action="action"
      multiple
      :file-list="fileList"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :on-error="handleError"
    >
      <!--      <i class="el-icon-upload"></i>-->
      <!--      <div class="el-upload__text">-->
      <!--        将文件拖到此处，或<em>点击上传</em>-->
      <!--      </div>-->
      <el-button
        type="primary"
        circle
        icon="el-icon-upload2"
      >
      </el-button>
      <div
        class="el-upload__tip"
        slot="tip"
      >
        文件最大不超过50MB
      </div>
    </el-upload>
  </div>
</template>

<script>
  import { getToken } from '@/service'

  export default {
    name: 'Upload',
    model: {
      prop: 'fileList',
      event: 'change'
    },
    props: {
      disabled: {
        type: Boolean,
        default: false
      },
      max: {
        type: Number,
        default: 5
      },
      fileList: {
        type: Array,
        default: () => []
      }
    },
    data () {
      return {
        action: `${GZL_URL}/file/upload`,
        headers: {
          'Authorization': getToken()
        }
      }
    },
    methods: {
      handleError (err) {
        this.$loading.done()
        try {
          const e = JSON.parse(err.message)
          this.$message.error(e.message)
        } catch (e) {
          this.$message.error('上传失败')
        }
      },
      handleRemove (file, fileList) {
        this.$emit('change', fileList)
      },
      handlePreview (file) {
        window.open(file.url)
      },
      handleAvatarSuccess (res, file) {
        this.$loading.done()
        const arr = this.fileList.map(item => ({ ...item }))
        arr.push({
          name: file.name,
          url: res.data
        })
        this.$emit('change', arr)
        this.$notify({
          title: '成功',
          message: `${file.name} 上传成功`,
          type: 'success'
        })
      },
      beforeAvatarUpload (file) {
        if (this.fileList.length >= this.max) {
          this.$message.error(`您最多只能上传${this.max}个文件`)
          return false
        }
        const isLtM = file.size / 1024 / 1024 < 50
        if (!isLtM) {
          this.$message.error('上传头像图片大小不能超过 50MB!')
          return false
        }
        this.$loading.start()
        return true
      }
    }
  }
</script>
<style>
  /*#gzl-upload .el-upload-dragger{*/
  /*  max-width: 100%;*/
  /*  width: 260px;*/
  /*  max-height: 160px;*/
  /*}*/
</style>
<style scoped>

</style>
